#include "createnewitem.h"
#include <QDebug>
CreateNewItem::CreateNewItem(QWidget *parent,QVBoxLayout * listP)
    : QDialog(parent)
{
    contentLabel=new QLabel("内容：");
    contentEdit=new QLineEdit;
    timeLabel=new QLabel("截止时间：");
    timeEdit=new QDateTimeEdit( QDateTime::currentDateTime(), this);
    enter=new QPushButton(tr("确定"));
    cancel=new QPushButton(tr("取消"));
    layout=new QGridLayout(this);
    layout->addWidget(contentLabel,0,0);
    layout->addWidget(contentEdit,0,1);
    layout->addWidget(timeLabel,1,0);
    layout->addWidget(timeEdit,1,1);
    QHBoxLayout * buttonLayout=new QHBoxLayout;
    buttonLayout->addWidget(enter);
    buttonLayout->addWidget(cancel);
    layout->addLayout(buttonLayout,2,0,1,2,Qt::AlignCenter);
    QPalette p=this->palette();
    p.setColor(QPalette::Window,Qt::yellow);
    setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    setWindowOpacity(0.8);
    setPalette(p);
    layout->setSizeConstraint(QLayout::SetFixedSize);
    connect(enter,SIGNAL(clicked(bool)),this,SLOT(pressOk()));
    connect(cancel,SIGNAL(clicked(bool)),this,SLOT(pressCancel()));
    this->listP=listP;
    //qDebug()<<"调用构造函数";
}
/*void CreateNewItem::bindButton()
{

}*/
void CreateNewItem::pressOk()
{
    QString content=contentEdit->text();
    if(content.isEmpty()||content.isNull())//如果未填写内容
    {
        QMessageBox::critical(this,tr("错误！"),tr("内容必须填写！"));
        return;
    }
    QDateTime dateTimeContent=timeEdit->dateTime();
    QDateTime nowTime=QDateTime::currentDateTime();
    int end=dateTimeContent.toTime_t(),start=nowTime.toTime_t();
   //qDebug()<<start<<"-"<<end<<"result is "<<end-start;
    if(end-start<=20)//如果设置的时间与现在时间不超过20秒
    {
        QMessageBox::critical(this,tr("错误！"),tr("无效时间！"));
        return;
    }
    if(listP!=NULL)
    {
        ItemDao::ItemData data;
        //data.
        ItemDao itemDao;
        data.id=itemDao.insertItem(content,dateTimeContent);
        if(data.id<0)
        {
            QMessageBox::critical(this,tr("错误！"),tr("数据库发生错误！"));
            return;
        }
        data.content=content;
        data.dateTime=dateTimeContent.toString("yyyy-MM-dd hh:mm:ss");
       // Dialog* temp=(Dialog*)parent();
       // parentP->addItem();
        listP->addWidget(new Item(this,data,listP));

      //  itemDao
    }
    this->flag=false;
    close();
}

void CreateNewItem::pressCancel()
{
   // *ok=false;
    this->flag=false;
    close();
}

void CreateNewItem::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton)
    {
        dragPosition=event->globalPos()-frameGeometry().topLeft();
        event->accept();
    }
}
void CreateNewItem::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton)
    {
        move(event->globalPos()-dragPosition);
        event->accept();
    }
}

